<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
      </el-form-item>
      <!-- <el-form-item label="退货金额" prop="price">
        <el-input v-model="queryParams.price" placeholder="请输入退货金额" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="退货原因" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入退货原因" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item> -->
      <el-form-item label="审核状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择审核状态" clearable size="small">
          <el-option label="待审核" :value="1" />
          <el-option label="通过" :value="2" />
          <el-option label="未通过" :value="3" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="退货单号" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入退货单号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item> -->
      <!-- <el-form-item label="商家物流发货时间" prop="businTime">
        <el-date-picker v-model="queryParams.businTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退货说明" show-overflow-tooltip align="center" prop="content" />
      <el-table-column label="退货图片" align="center" prop="urls" width="120">
        <template v-slot="scope">
          <div class="imgbox" v-if="scope.row.urls.length !== 0">
            <img @click="clickimg(scope.row.urls[scope.row.imgIndex])" class="imgstyle" :src="scope.row.urls[scope.row.imgIndex]" alt="">
            <div class="toleftstyle" @click="toleft(scope.$index,scope.row.urls.length,scope.row.imgIndex)"><i class="el-icon-arrow-left"></i></div>
            <div class="torightstyle" @click="toright(scope.$index,scope.row.urls.length,scope.row.imgIndex)" ><i class="el-icon-arrow-right"></i></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="退货金额" align="center" prop="price" />
      <el-table-column label="退货原因" show-overflow-tooltip align="center" prop="title" />
      <!-- <el-table-column label="退货/换货" align="center" prop="type">
        <template v-slot="scope">
          <span>{{ istype[scope.row.type] }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="退款状态" align="center" prop="payStatus">
        <template v-slot="scope">
          <span>{{ ispayStatus[scope.row.payStatus] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="status" >
        <template v-slot="scope">
          <span>{{ istoNoto[scope.row.status] }}</span>
          <!-- 1待审核2通过3未通过 -->
        </template>
      </el-table-column>
      <el-table-column label="确认状态" align="center" prop="confirmStatus">
        <template v-slot="scope">
          <span>{{ isconfirmStatus[scope.row.confirmStatus] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="流程状态" align="center" prop="refundStatus">
        <template v-slot="scope">
          <span>{{ isrefundStatus[scope.row.refundStatus] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退货单号" align="center" prop="code" />
      <el-table-column label="订单编号" align="center" prop="orderCode" />
      <!-- <el-table-column label="商品" align="center" prop="goods" /> -->
      <el-table-column label="用户物流信息" align="center" prop="logistic">
        <template v-slot="scope">
          <el-button v-show="scope.row.logisTime !== null" size="mini" type="text"  @click="handleLogistics(scope.row)">查看用户物流</el-button>
        </template>
      </el-table-column>
      <el-table-column label="商家物流信息" align="center" prop="businLogistic">
        <template v-slot="scope">
          <el-button v-show="scope.row.confirmStatus == 3 && scope.row.businTime !== null" size="mini" type="text"  @click="handleShangLogistics(scope.row)">查看商家物流</el-button>
        </template>
      </el-table-column>
      <el-table-column label="物流发货时间" align="center" prop="logisTime">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.logisTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商家物流发货时间" align="center" prop="businTime">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.businTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column  fixed="right"  label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button> -->
          <el-button v-show="scope.row.status === 1" size="mini" type="text" @click="handleto(scope.row)">通过</el-button>
          <el-button v-show="scope.row.status === 1" size="mini" type="text" @click="handleNoto(scope.row)">不通过</el-button>
          <!-- <el-button v-show="scope.row.status === 2 && scope.row.type === 2" size="mini" type="text" @click="handleDelete(scope.row)">填写物流信息</el-button> -->
          <el-button v-show="scope.row.confirmStatus == 3 && scope.row.refundStatus == 6"  size="mini" type="text"  @click="handleShipments(scope.row)">发货</el-button>
          <!-- <el-button v-show="scope.row.logisTime !== null" size="mini" type="text"  @click="handleLogistics(scope.row)">查看用户物流</el-button> -->
          <!-- <el-button v-show="scope.row.logisTime !== null" size="mini" type="text"  @click="handleShangLogistics(scope.row)">查看商家物流</el-button> -->
          <el-button v-show="scope.row.status === 2 && scope.row.logisTime !== null && scope.row.confirmStatus === 1" size="mini" type="text"  @click="handleComfirm(scope.row,2,'确认')">确认</el-button>
          <el-button v-show="scope.row.status === 2 && scope.row.logisTime !== null && scope.row.confirmStatus === 1" size="mini" type="text"  @click="handleComfirm(scope.row,3,'驳回')">驳回</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 发货弹窗 -->
    <el-dialog :title="title" :visible.sync="shipmentsopen" width="600px" v-dialogDrag append-to-body>
      <el-form ref="shipmentsform" :model="shipmentsform" :rules="shipmentsrules" label-width="100px">
        <el-form-item label="订单编号" prop="code">
          <el-input disabled v-model="shipmentsform.code" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="物流公司" prop="name">
          <el-select filterable @change="changename" v-model="shipmentsform.name" placeholder="请选择物流公司" clearable size="small">
            <el-option v-for="item in wuliuList" :label="item.name" :value="item.name" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="物料单号" prop="num">
          <el-input v-model="shipmentsform.num" placeholder="请输入物料单号" />
        </el-form-item>
        <!-- <el-form-item label="运费" prop="price">
          <el-input v-model="shipmentsform.price" placeholder="请输入运费" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="shipmentssubmitForm">确 定</el-button>
        <el-button @click="shipmentsopen =false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 物流弹窗 -->
    <el-dialog :title="title" :visible.sync="logisticsopen" width="800px" v-dialogDrag append-to-body>
      <div>
        <div style="font-size:18px;display:flex;justify-content: space-between;margin-bottom:20px;">
          <span>物流公司：{{logisticsform.com}}</span>
          <span>物流编号：{{logisticsform.nu}}</span>
        </div>
        <el-steps direction="vertical" :active="1">
          <el-step v-for="(item,index) in logisticsform.data" :key="index+'a'" :title="item.ftime" :description="item.context"></el-step>
        </el-steps>
      </div>
    </el-dialog>
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="500px" v-dialogDrag append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="退货说明">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="退货图片" prop="urls">
          <el-input v-model="form.urls" placeholder="请输入退货图片" />
        </el-form-item>
        <el-form-item label="退货金额" prop="price">
          <el-input v-model="form.price" placeholder="请输入退货金额" />
        </el-form-item>
        <el-form-item label="退货原因" prop="title">
          <el-input v-model="form.title" placeholder="请输入退货原因" />
        </el-form-item>
        <el-form-item label="1退货2换货" prop="type">
          <el-select v-model="form.type" placeholder="请选择1退货2换货">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态1待审核2通过3未通过" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="退货单号" prop="code">
          <el-input v-model="form.code" placeholder="请输入退货单号" />
        </el-form-item>
        <el-form-item label="商品" prop="goods">
          <el-input v-model="form.goods" placeholder="请输入商品" />
        </el-form-item>
        <el-form-item label="物流信息" prop="logistic">
          <el-input v-model="form.logistic" placeholder="请输入物流信息" />
        </el-form-item>
        <el-form-item label="商家物流信息" prop="businLogistic">
          <el-input v-model="form.businLogistic" placeholder="请输入商家物流信息" />
        </el-form-item>
        <el-form-item label="物流发货时间" prop="logisTime">
          <el-date-picker clearable v-model="form.logisTime" type="date" value-format="timestamp" placeholder="选择物流发货时间" />
        </el-form-item>
        <el-form-item label="商家物流发货时间" prop="businTime">
          <el-date-picker clearable v-model="form.businTime" type="date" value-format="timestamp" placeholder="选择商家物流发货时间" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <magnifyImg v-if="imgboxShow" :imgurl="imgurl" />
  </div>
</template>

<script>
import { createBack, updateBack, deleteBack, getBack, getBackPage, exportBackExcel } from "@/api/qd/back";
import Editor from '@/components/Editor';

export default {
  name: "Back",
  components: {
    Editor
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 退/换货列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        createTime: [],
        content: null,
        urls: null,
        price: null,
        title: null,
        type: null,
        status: null,
        code: null,
        goods: null,
        orderId: null,
        logistic: null,
        businLogistic: null,
        logisTime: [],
        businTime: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        type: [{ required: true, message: "1退货2换货不能为空", trigger: "change" }],
        status: [{ required: true, message: "审核状态1待审核2通过3未通过不能为空", trigger: "blur" }],
        code: [{ required: true, message: "退货单号不能为空", trigger: "blur" }],
      },
      istoNoto:{1:'待审核',2:'通过',3:'未通过'},  // 审核状态
      istype:{1:'退货',2:'换货'},
      isconfirmStatus:{1:'待确认',2:'已确认',3:'驳回'},  // 确认状态
      isrefundStatus:{1:'商家待审核',2:'申请审核失败',3:'用户待发货',4:'用户发货中',5:'退款已完成',6:'退款驳回',7:'商家已发货'}, //流程状态
      ispayStatus:{1:'成功',2:'失败'}, // 支付状态
      // 发货弹窗
      shipmentsopen:false,
      shipmentsform:{},
      shipmentsrules:{
        name:[{required:true,message:'物流公司不能为空',trigger:'change'}],
        num:[{required:true,message:'物料单号不能为空',trigger:'blur'}]
      },
      wuliuList:[],
      // 物流弹窗
      logisticsform:{},
      logisticsopen:false,
      imgurl:null, // 图片
    };
  },
  created() {
    this.getList();
    this.getwuliuList()
  },
  computed:{
    imgboxShow(){
      return this.$store.state.tong.imgStatus
    }
  },
  methods: {
    handleComfirm(row,num,str){  // 确定/驳回按钮
      this.$confirm(`是否确定${str}此单？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios({url:'/qd/back/confirm',method:'get',params:{id:row.id,status:num}}).then(res=>{
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.getList()
          }).catch(rej=>{
            this.$message({
              type: 'error',
              message: '操作失败，请确认是否退款，再执行下一步操作'
            });
          })
          
        })
    },
    handleShipments(row){  // 发货按钮
      this.shipmentsform = {
        id:row.id,
      }
      this.shipmentsopen = true
    },
     shipmentssubmitForm(){  // 发货弹窗确定
     const obj = {
      id:this.shipmentsform.id,
      vo:{
        code:this.shipmentsform.code,
        name:this.shipmentsform.name,
        num:this.shipmentsform.num
      }
     }
      this.$axios({url:'/qd/back/delivery',method:'post',data:obj}).then(res=>{
        this.$message.success('发货成功')
        this.shipmentsopen = false
        this.getList()
      })
    },
    changename(e){ // 选择物流名称时执行
      const code = this.wuliuList.filter(item=>item.name === e)[0].code
      this.$set(this.shipmentsform,'code',code)
    },
    clickimg(url){  // 点击图片
      this.imgurl = url
      this.$store.commit('tong/changeImgstaus',true)
    },
    handleLogistics(row){ // 查看用户物流按钮
      this.$axios({url:'/qd/back/findLogistics?id='+row.id,method:'get'}).then(res=>{
        this.logisticsform = res.data ?? {}
        this.logisticsopen = true
      })
    },
    handleShangLogistics(row){ // 查看商家物流按钮
      this.$axios({url:'/qd/back/findBusinLogistics?id='+row.id,method:'get'}).then(res=>{
        this.logisticsform = res.data ?? {}
        this.logisticsopen = true
      })
    },
    getwuliuList(){ // 查看物流信息
      this.$axios({url:'/qd/logistics/getList',method:'get'}).then(res=>{
        this.wuliuList = res.data ?? []
      })
    },
    handleto(row){ //通过
    // 如果为待发货 退货 orderStatus = 2
      this.$confirm(`${row.orderStatus==2?'商品订单为待发货状态下,点击通过会直接退款':'此操作为通过，是否确定通过？'}`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios({url:'/qd/back/auditing',method:'get',params:{id:row.id,status:2}}).then(res=>{
            this.$message({
              type: 'success',
              message: '通过成功!'
            });
            this.getList()
          })
          
        })
    },
    handleNoto(row){  // 不通过
    // 如果为待发货 退货 orderStatus = 2
      this.$confirm(`${row.orderStatus==2?'商品订单为待发货状态下,点击不通过会直接回到订单原来状态。':'此操作为不通过，是否确定不通过？'}`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios({url:'/qd/back/auditing',method:'get',params:{id:row.id,status:3}}).then(res=>{
            this.$message({
              type: 'success',
              message: '通过成功!'
            });
            this.getList()
          })
          
        })
    },
    toleft(index,imglength,iindex){  // 图片向右
        if(iindex === 0) return this.list[index].imgIndex = imglength - 1 ?? 0
        this.list[index].imgIndex -= 1
    },
    toright(index,imglength,iindex){  // 图片向左
        if(imglength - 1 === iindex) return this.list[index].imgIndex = 0
        this.list[index].imgIndex += 1
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getBackPage({...this.queryParams,type:1}).then(response => {
        this.list = response.data.list;
        this.list.forEach(item=>{
          this.$set(item,'imgIndex',0)
        })
        this.total = response.data.total;
        this.loading = false;
        
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        content: undefined,
        urls: undefined,
        price: undefined,
        title: undefined,
        type: undefined,
        status: undefined,
        code: undefined,
        goods: undefined,
        orderId: undefined,
        logistic: undefined,
        businLogistic: undefined,
        logisTime: undefined,
        businTime: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加退/换货";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getBack(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改退/换货";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateBack(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createBack(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除?').then(function() {
          return deleteBack(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有退/换货数据项?').then(() => {
          this.exportLoading = true;
          return exportBackExcel(params);
        }).then(response => {
          this.$download.excel(response, '退/换货.xls');
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
<style lang="scss" scoped>
@import "../../styles/minImgStyle.scss";

</style>